package tool;

import haxe.io.Bytes;
import hxd.Pixels;

class PixelTool {
    public static function ColorsToPixels(colors, width, height) {
        var size = width * height;
        var bytes = Bytes.alloc(size * 4);
        for (i in 0 ... size){
            var color = colors[i];
            var b = color & 0xff;
            var g = (color >> 8) & 0xff;
            var r = (color >> 16) & 0xff;
            color = r | (g << 8) | (b << 16);
            var alpha = 0xff;
            var t = color | alpha << 24;
            bytes.setInt32(4 * i, t);
        }
        var pixels = new Pixels(width, height, bytes, RGBA);
        return pixels;
    }

    //转成固定大小colors
    public static function PixelToColors(pixels:Pixels, width, height) {
        var tx = pixels.width / width;
        var ty = pixels.height / height;
        var colors = new Array<Int>();
        colors.resize(width * height);
        //var pcolors = pixels.toVector();
        var pw = pixels.width;
        var ph = pixels.height;
        for (x in 0 ... width) for (y in 0 ... height){
            var sx = x * tx;
            var ex = (x + 1) * tx;
            var sy = y * ty;
            var ey = (y + 1) * ty;
            var cx = sx;
            var cy = sy;
            var sr = 0.0;
            var sg = 0.0;
            var sb = 0.0;
            var sw = 0.0;

            while (cx < ex){
                var ix = Math.ceil(cx);
                var nx = Math.min(ix + 1, ex);
                cy = sy;
                while (cy < ey){
                    var iy = Math.ceil(cy);
                    var ny = Math.min(iy + 1, ey);
                    var w = (nx - cx) * (ny - cy);
                    var color = pixels.getPixel(ix, iy);
                    var r = (color >> 16) & 0xff;
                    var g = (color >> 8) & 0xff;
                    var b = color & 0xff;
                    sr += r * w;
                    sg += g * w;
                    sb += b * w;
                    sw += w;

                    cy = ny;
                }
                
                cx = nx;
            }
            var r = Math.round(sr / sw);
            var g = Math.round(sg / sw);
            var b = Math.round(sb / sw);
            var fcolor = (r << 16) | (g << 8) | b;
            colors[x + y * width] = fcolor;
        }
        return colors;
    }
}